package base.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * AuthorizeFilter
 *
 * @author 姜治昊
 * @time 2017年12月13日 下午10:10:16
 */
public class AuthorizeFilter implements Filter{

	private static String[] NO_NEED_LOGIN_URL = null;
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) arg0;
		HttpServletResponse resp = (HttpServletResponse) arg1;
		HttpSession session = req.getSession();
		if(notNeedLogin(req.getRequestURI())) {
			arg2.doFilter(arg0, arg1);
		} else {
			Object obj = session.getAttribute("LOGIN_USER");
			if(null == obj) {
				gotoLoginPage(req, resp);
			} else {
				arg2.doFilter(arg0, arg1);
			}
		}
		return ;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		String param = arg0.getInitParameter("NO_NEED_LOGIN_URL");
		NO_NEED_LOGIN_URL = param.split("-");
	}
	
	/**
	 * 跳转到登录界面
	 * @param request
	 * @param response
	 */
	public void gotoLoginPage(HttpServletRequest request, HttpServletResponse response) {
		String loginUrl = request.getContextPath() + "/sys/page/login";
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println("<html>");  
		    out.println("<script>");  
		    out.println("window.open ('"+loginUrl+"','_top')"); 
		    out.println("</script>");  
		    out.println("</html>");  
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
	
	/**
	 * 判断是否需要登陆后访问
	 * @param url 
	 */
	public boolean notNeedLogin(String toUrl) {
		for(String url : NO_NEED_LOGIN_URL) {
			if(toUrl != null && toUrl.indexOf(url) >= 0) {
				return true;
			}
		}
		return false;
	}

}
